package com.mhs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mhs.entity.Article;
import com.mhs.entity.ArticleImgs;
import com.mhs.entity.Comment;
import com.mhs.entity.User;
import com.mhs.exception.BizException;
import com.mhs.feign.remote.IUserService;
import com.mhs.mapper.ArticleImgsMapper;
import com.mhs.mapper.ArticleMapper;
import com.mhs.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mhs.service.ICommentService;
import com.mhs.utils.BaseContext;
import com.mhs.utils.RedisCache;
import com.mhs.vo.ArticleVo;
import com.mhs.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Fantasy0521
 * @since 2023-04-09
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

//    @Resource
//    private RedisCache redisCache;

    @Resource
    private ArticleImgsMapper articleImgsMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisCache redisCache;


    /**
     * 发布咨询帖
     *
     * @param article
     * @return
     */
    @Override
    @Transactional
    public Result send(ArticleVo article) {
        //1 获取贴子信息
        //获取当前用户
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new RuntimeException(new BizException("无法获取当前用户"));
        }
        article.setUserId(currentId);//必须先登陆
        article.setCreateTime(LocalDateTime.now());
//        article.setDescription(article.getContent());
        //获取imgs
        List<String> imgs = article.getImgs();
        if (imgs == null || imgs.size() == 0) {//如果用户没有上传图片
            articleMapper.insert(article);
            return Result.success("发布成功");
        }
        //默认将用户上传的第一张图片设置为文章首图
        article.setFirstPicture(imgs.get(0));
        articleMapper.insert(article);

        //2 获取imgs 存入 article_imgs表
        Long id = article.getId();
        ArticleImgs articleImgs = new ArticleImgs();
        articleImgs.setArticleId(id);

        for (String img : imgs) {
            articleImgs.setImg(img);
            articleImgsMapper.insert(articleImgs);
        }
        //从redis删除
        redisCache.deleteObject("articlePage");
        return Result.success("发布成功");
    }

    @Value("${download.url}")
    private String downloadUrl;

    /**
     * 分页查询文章列表
     *
     * @param page
     * @param pageSize
     * @return 文章列表以及文章所有图片和评论数和点赞数
     */
    @Override
    public Result getArticleListByPage(Integer page, Integer pageSize) {
        //尝试从redis缓存中获取
        Object cacheObject = redisCache.getCacheObject("articlePage");
        if (cacheObject != null) {
            return Result.success("获取成功", cacheObject);
        }
        //分页查询
        //根据是否置顶以及点赞数来排序,以及要查询出评论数,点赞数和所有图片
        List<ArticleVo> articleVos = articleMapper.selectPageOrder((page - 1) * pageSize, pageSize);
        //统计评论数,前端方便获取
        for (ArticleVo articleVo : articleVos) {
            List<String> imgs = new ArrayList<>();
            for (String img : articleVo.getImgs()) {
                img = downloadUrl + img;
                imgs.add(img);
            }
            articleVo.setImgs(imgs);
            articleVo.setCommentCount(articleVo.getComments().size());
            //用户头像
            Long userId = articleVo.getUserId();
            User userById = userService.getUserById(userId);
            articleVo.setAvatar(userById.getAvatar());
        }
        //传给前端一个分页对象
        Page<ArticleVo> pageResult = new Page<>();
        pageResult.setRecords(articleVos);
//        pageResult.setTotal(articleVos.size());
        int size = articleMapper.selectList(new LambdaQueryWrapper<Article>().eq(Article::getIsPublished, true)).size();
        pageResult.setTotal(size);
        //存入缓存
        redisCache.setCacheObject("articlePage",pageResult);
        return Result.success("获取成功", pageResult);
    }

    @Resource
    private IUserService userService;
    
    @Resource
    private ICommentService commentService;

    @Override
    public Result getArticleById(Integer articleId) {
        Article article = this.getById(articleId);
        //使用ArticleVo来封装,目的是把图片也一起传过去
        ArticleVo articleVo = new ArticleVo();
        //对象拷贝
        BeanUtils.copyProperties(article, articleVo);
        LambdaQueryWrapper<ArticleImgs> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ArticleImgs::getArticleId, articleId);
        List<ArticleImgs> articleImgs = articleImgsMapper.selectList(lambdaQueryWrapper);
        //对图片路径进行处理
        List<String> imgs = new ArrayList<>();
        for (ArticleImgs articleImg : articleImgs) {
            String img = downloadUrl + articleImg.getImg();
            imgs.add(img);
        }
        articleVo.setImgs(imgs);
        //查询总评论数
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId,articleId);
        int count = commentService.count(queryWrapper);

        articleVo.setCommentCount(count);

        //查询用户信息
        //远程调用查询用户信息  或者  直接修改sql把user也一起查出来
        //远程调用
        Long userId = articleVo.getUserId();
        User user = userService.getUserById(userId);

        if (user != null) {
            articleVo.setAvatar(user.getAvatar());
            articleVo.setNickName(user.getNickName());
        }

        return Result.success(articleVo);
    }

    /**
     * 点赞 数据库pick + 1
     * @param articleId
     * @return
     */
    @Override
    public Result pick(Integer articleId) {
        if (articleId == null) {
            throw new RuntimeException(new BizException("文章Id不能为空"));
        }
        articleMapper.updatePick(articleId);
        return Result.success("点赞成功!");
    }


}
